/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bpmlab.shift.conversores;

import bpmlab.shift.dao.DAOFactory;
import bpmlab.shift.dao.JpaUtil;
import bpmlab.shift.dao.service.GenericDAO;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 *
 * @author Simeia Lima
 * @param <T>
 */
public class GenericConverter<T> implements Converter {

    private final GenericDAO<T> dao;
    private final Class<T> clazz;

    public GenericConverter(Class<T> clazz) {
        this.clazz = clazz;
        dao = DAOFactory.criarGenericDAO(clazz);
    }

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
        if (string.isEmpty()) {
            try {
                return clazz.newInstance();
            } catch (InstantiationException | IllegalAccessException ex) {
            }
        }
        return dao.obter(new Long(string));
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
        if (o == null) {
            return "";
        }
        Object id = getId(o);
        if (id == null) {
            return "";
        } else {
            return id.toString();
        }
    }

    private Object getId(Object o) {
        try {
            System.out.println(o.getClass());
            Field field = o.getClass().getDeclaredField("id");
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            return field.get(o);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}
